var rain = (function(){
  var R = {};
  var interTime = 1000 * 60 * 10;
  var interRefresh;
  var markers=[];
  var liang={};
  var beginTime, endTime;
  var hourData;
  
  R.init = function(){
    $(".floattool .graphic_nav #viewTable").off().on("click", function(){
      if($(":hidden#dialogWin").length==1){
        R.buildData();
        $("#dialogWin").show();
      }else{
        $("#dialogWin").hide();
      }
      $("#dialogWin .close").off().on("click", function(){
        $("#dialogWin").hide();
      });
    });
    $(".floattool .graphic_nav .icon").off().on("click", function(){
      $(".floattool .graphic_nav .layer-pop").show(function(){
        $(".floattool .graphic_nav .layer-pop .close").off().on("click", function(){
          $(".floattool .graphic_nav .layer-pop").hide();
        });
        $(".floattool .graphic_nav .layer-pop .layer-arguments .check, .floattool .graphic_nav .layer-pop .layer-arguments .uncheck").off().on("click", function(){
          var tag = $(this).attr("data-tag");
          if($(this).hasClass("check")){
            $(this).removeClass("check");
            $(this).addClass("uncheck")
            if(tag == 'switch'){
              R.disabled();
            }else if(tag == 'stationName'){
              R.viewMarkers();
            }
          }else{
            $(this).removeClass("uncheck");
            $(this).addClass("check");
            if(tag == 'switch'){
              if(getLoginInfo().username=='anren'){
                R.tip("您未获得授权，请联系网站管理员。")
                $(this).addClass("uncheck");
                $(this).removeClass("check");
                return false;
              }
              R.disabled();
              R.enabled();
            }else if(tag == 'stationName'){
              R.viewMarkers();
            }
          }
        });
      });
    });
    $(".floattool .graphic_nav :radio[name=hour]").off().on("change", function(o){
      R.viewMarkers();
    });
    $(".floattool .graphic_nav :radio[name=query]").off().on("change", function(o){
      if(o.target.value==1){
        R.chooseOne();
        R.getByHourAndAreaIds();
      }
      if(o.target.value==2){
        $("#beginTime").off().on("click", function(){
          WdatePicker({el: this, maxDate:'%y-%M-%d %H',isShowClear:true,readOnly:true,dateFmt:'yyyy-MM-dd HH'})
        });
        $("#endTime").off().on("click", function(){
          WdatePicker({el: this, maxDate:'%y-%M-%d %H',isShowClear:true,readOnly:true,dateFmt:'yyyy-MM-dd HH'});
        });
        $("#beginTime").css("width", '110px');
        $("#beginTime").parent().show();
        $("#endTime").css("width", '110px');
        $("#endTime").attr("placeholder", "结束时间");
        $("label", $("#endTime").parent()).text("结束时间：");
        $(".item1").hide();
        $(".item2").show();
        $(":radio[name=hours]:first")[0].checked=true;
        var now = new Date();
        $("#endTime").val(now.format("yyyy-MM-dd hh"));
        now.setHours(now.getHours() - 1);
        $("#beginTime").val(now.format("yyyy-MM-dd hh"));
        R.getByHourAndAreaIds();
      }
      if(o.target.value==3){
        $("#beginTime").off().on("click", function(){
          WdatePicker({el: this, maxDate:'%y-%M-%d %H:%m',isShowClear:true,readOnly:true,dateFmt:'yyyy-MM-dd HH:mm'})
        });
        $("#endTime").off().on("click", function(){
          WdatePicker({el: this, maxDate:'%y-%M-%d %H:%m',isShowClear:true,readOnly:true,dateFmt:'yyyy-MM-dd HH:mm'});
        });
        $("#beginTime").css("width", '125px');
        $("#beginTime").parent().show();
        $("#endTime").css("width", '125px');
        $("#endTime").attr("placeholder", "结束时间");
        $("label", $("#endTime").parent()).text("结束时间：");
        $(".item1").hide();
        $(".item2").show();
        $(":radio[name=hours]:first")[0].checked=true;
        var now = new Date();
        $("#endTime").val(now.format("yyyy-MM-dd hh:mm"));
        now.setMinutes(now.getMinutes() - 30);
        $("#beginTime").val(now.format("yyyy-MM-dd hh:mm"));
        R.getByMinuteAndAreaIds();
      }
    });
    
    R.chooseOne();
    
    map.on("zoomchange", function(){
      R.viewMarkers();
    })
  };
  
  R.buildData = function(){
    var trs = new Array();
    var h = $(".floattool .graphic_nav :radio[name=hour]:checked").val();
    var choose = $(".floattool .graphic_nav :radio[name=query]:checked").val();
    var title = "郴州市 过去" + h + "小时降水量 大于0情况表(单位:mm)";
    if(choose != 1){
      title = "郴州市 降水量 大于0情况表(单位:mm)";
    }
    var totalMian = 0, gte1 = 0, gte10 = 0, gte25 = 0, gte50 = 0, gte100 = 0, gte200 = 0, maxName = "", maxValue = 0, maxHourName = "", maxHourValue = 0;
    for(var areaCode in liang){
      var td="";
      var count = 0, sum = 0;
      liang[areaCode].sort(function(a, b){
        var av = a['pre'+h+'h'] * 1;
        var bv = b['pre'+h+'h'] * 1;
        if(choose != 1){
          av = a.pre * 1;
          bv = b.pre * 1;
        }
        return bv - av;
      });
      liang[areaCode].forEach(function(im){
        var val = im['pre'+h+'h'] * 1;
        if(choose != 1){
          val = im.pre * 1;
        }
        if(val > 0){
          if(count % 5 == 0 && count > 0){
            td += "</tr><tr><td></td><td></td>";
          }
          count ++;
          sum += val;
          td += "<td>" + im.name + "</td><td>"+val+"</td>";
          if(val >= 0.1){
            gte1 ++;
          }else if (val >= 10){
            gte10 ++;
          }else if (val >= 25){
            gte25 ++;
          }else if (val >= 50){
            gte50 ++;
          }else if (val >= 100){
            gte100 ++;
          }else if (val >= 200){
            gte200 ++;
          }
          if(val > maxValue){
            maxValue = val;
            maxName = im.name;
          }
        }
      });
      if(sum > 0){
        if(count < 6){
          for(var j = 1; j < 6-count; j++){
            td += "<td></td><td></td>";
          }
        }
        var mian = sum / count;
        td = "<tr><td>" + areaNames[areaCode] + "</td><td style='color:green;font-weight:bold'>"+mian.toFixed(2)+"</td>" + td;
        trs.push({"mian": mian, "html": td + "</tr>"});
        totalMian += mian;
      }
    }
    maxHourName = hourData["maxNameH"+ h]
    maxHourValue = hourData["maxValueH"+ h]
    var bb = new Date(Date.parse(beginTime.replace(/-/g,"/")));
    var ee = new Date(Date.parse(endTime.replace(/-/g,"/")));
    
    var temp2 = "小时";
    var temp = bb.format("d日hh时") + " 到 " + ee.format("d日hh时");
    if(choose == 3){
      temp = bb.format("d日hh时mm分") + " 到 " + ee.format("d日hh时mm分");
      temp2 = "分钟";
      maxHourName = maxName;
      maxHourValue = maxValue;
    }
    if(choose == 1){
      temp += "，过去"+h+"小时";
    }else if(choose == 2){
      ms = ee.getTime() - bb.getTime();
      h = Math.floor(ms / 1000 / 60 / 60);
      temp += "，共"+h+"小时";
    }else if(choose == 3){
      ms = ee.getTime() - bb.getTime();
      h = Math.floor(ms / 1000 / 60);
      temp += "，共"+h+"分钟";
    }
    
    var subTitle = bb.format("yyyy年MM月dd日hh时") + " 到 " + ee.format("yyyy年MM月dd日hh时") + "("+h+temp2+")";
    if(choose == 3){
      subTitle = bb.format("yyyy年MM月dd日hh时mm分") + " 到 " + ee.format("yyyy年MM月dd日hh时mm分") + "("+h+temp2+")";
    }
    
    $("#dialogWin .title").text(title);
    $("#dialogWin .subtitle").text(subTitle);
    $("#dialogWin .footer").html("根据最新自动气象站监测，" + temp + "，总面雨量为"+totalMian.toFixed(2)+"毫米，:≥0.1mm的站数为"+gte1+"个;≥10.0mm的站数为"+gte10+"个;≥25.0mm的站数为"+gte25+"个;≥50.0mm的站数为"+gte50+"个;≥100.0mm的站数为"+gte100+"个;＞200mm的站数为"+gte200+"个;<br>最大累积降水出现在"+maxName+"为"+maxValue+"毫米，最大"+temp2+"雨强出现在"+maxHourName+"为"+maxHourValue+"毫米。");
    trs.sort(function(a, b){
      return b.mian - a.mian;
    });
    var htmls = [];
    trs.forEach(function(ar){
      htmls.push(ar.html);
    });
    $("#dialogWin .beautiful-table").html(htmls.join(""));
    Scrollbar.init(document.querySelector('.foo--inside--dialog'));
    var hei = $("#dialogWin").height() - 25 - 25 - 25 - 62
    $("#dialogWin .tablediv").height(hei);
  };
  
  R.chooseOne = function(){
    $("#beginTime").off().on("click", function(){
      WdatePicker({el: this, maxDate:'%y-%M-%d %H',isShowClear:true,readOnly:true,dateFmt:'yyyy-MM-dd HH'})
    });
    $("#endTime").off().on("click", function(){
      WdatePicker({el: this, maxDate:'%y-%M-%d %H',isShowClear:true,readOnly:true,dateFmt:'yyyy-MM-dd HH'});
    });
    $("#beginTime").parent().hide();
    $("#endTime").css("width", '110px');
    $("#endTime").attr("placeholder", "查询时间");
    $("label", $("#endTime").parent()).text("查询时间：");
    $(".item1").show();
    $(".item2").hide();
    $(":radio[name=hour]:first")[0].checked=true;
    var now = new Date();
    $("#endTime").val(now.format("yyyy-MM-dd hh"));
    now.setHours(now.getHours() - 1);
    $("#beginTime").val(now.format("yyyy-MM-dd hh"));
  };
  R.enabled = function(){
    $(".floattool .graphic_nav .layer-pop .oooother").hide();
    R.getByHourAndAreaIds();
    
    interRefresh = setInterval(function(){
      R.getByHourAndAreaIds();
    }, interTime);
  };
  
  R.disabled = function(){
    $(".floattool .graphic_nav .layer-pop .oooother").css("height", $(".floattool .graphic_nav .layer-pop").height()-56);
    $(".floattool .graphic_nav .layer-pop .oooother").show();
    clearInterval(interRefresh);
    map.remove(markers);
    markers=[];
  };
  
  R.query = function(){
    var choose = $(".floattool .graphic_nav :radio[name=query]:checked").val();
    if(choose <= 2){
      R.getByHourAndAreaIds();
    }else{
      R.getByMinuteAndAreaIds();
    }
  };
  R.getByHourAndAreaIds = function(){
    var choose = $(".floattool .graphic_nav :radio[name=query]:checked").val();
    var h = $(".floattool .graphic_nav :radio[name=hour]:checked").val();
    beginTime = $("#beginTime").val();
    endTime = $("#endTime").val();
    if(choose == 1){
      endTime += ":00:00";
      var d = new Date(Date.parse(endTime.replace(/-/g,"/")));
      d.setDate(d.getDate()-1);
      beginTime = d.format("yyyy-MM-dd hh:mm:ss");
    }else if(choose == 2){
      beginTime += ":00:00";
      endTime += ":00:00";
    }else{
      beginTime += ":00";
      endTime += ":00";
    }
    var params = {
      "areaIds": 431000,
      "beginTime": beginTime,
      "endTime": endTime
    };
    console.log(JSON.stringify(params))
    ajax({
      url: '/api/cimiss/data/areas/for/hour',
      contentType: 'application/json',
      data: params,
      success: function(data){
        items = data.items;
        hourData = data;
        map.remove(markers);
        markers=[];
        liang={};
        if(choose == 1){
          var d = new Date(Date.parse(endTime.replace(/-/g,"/")));
          d.setHours(d.getHours()-(h*1));
          beginTime = d.format("yyyy-MM-dd hh:mm:ss");
        }
        if(items.length > 0){
          R.tip("时间段[" + beginTime + "，" + endTime + "]的降水量分布");
          items.forEach(function(item){
            var yu = liang[item.areaCode];
            if(yu == null){
              yu = new Array();
              liang[item.areaCode] = yu;
            }
            yu.push({'name': item.stationName, 'pre': item.pre.toFixed(1), 'pre1h': item.pre1h.toFixed(1), 'pre3h': item.pre3h.toFixed(1), 'pre6h': item.pre6h.toFixed(1), 'pre12h': item.pre12h.toFixed(1), 'pre24h': item.pre24h.toFixed(1)});
            var marker = new RainMarker({
              lng: item.lng,
              lat: item.lat,
              text: {
                value: "<div class='stationDataClass' data-pre1h='"+item.pre1h.toFixed(1)+"' data-pre3h='"+item.pre3h.toFixed(1)+"' data-pre6h='"+item.pre6h.toFixed(1)+"' data-pre12h='"+item.pre12h.toFixed(1)+"' data-pre24h='"+item.pre24h.toFixed(1)+"'><label>" + (item.pre1h.toFixed(1)) + "</label><span>"+item.stationName+"</span></div>",
                color: 'green',
                size: '20px',
                weight: '400',
              },
              point: {
                color: 'green',
                radius: 4,
                overColor: '#095c09'
              },
              click: function(e){
                console.log(e)
              }
            });
            marker.data = item;
            marker.on("mouseover", R.mouseover);
            marker.on("mouseout", R.mouseout);
            markers.push(marker);
          });
          R.viewMarkers();
        }else{
          R.tip("时间段[" + btime + "，" + endTime + "]，没有降水量");
        }
      }
    });
  };
  R.getByMinuteAndAreaIds = function(){
    beginTime = $("#beginTime").val();
    endTime = $("#endTime").val();
    beginTime += ":00";
    endTime += ":00";
    var params = {
      "areaIds": 431000,
      "beginTime": beginTime,
      "endTime": endTime
    };
    console.log(JSON.stringify(params))
    ajax({
      url: '/api/cimiss/data/areas/for/minute',
      contentType: 'application/json',
      data: params,
      success: function(items){
        map.remove(markers);
        markers=[];
        liang={};
        if(items.length > 0){
          R.tip("时间段[" + beginTime + "，" + endTime + "]的降水量分布");
          btime = beginTime;
          etime = endTime;
          items.forEach(function(item){
            var yu = liang[item.areaCode];
            if(yu == null){
              yu = new Array();
              liang[item.areaCode] = yu;
            }
            yu.push({'name': item.stationName, 'pre': item.pre.toFixed(1), 'pre1h': item.pre.toFixed(1), 'pre3h': item.pre.toFixed(1), 'pre6h': item.pre.toFixed(1), 'pre12h': item.pre.toFixed(1), 'pre24h': item.pre.toFixed(1)});
            var marker = new RainMarker({
              lng: item.lng,
              lat: item.lat,
              text: {
                value: "<div class='stationDataClass'><label>" + (item.pre.toFixed(1)) + "</label><span>"+item.stationName+"</span></div>",
                color: item.color,
                size: '20px',
                weight: '400',
              },
              point: {
                color: 'green',
                radius: 4,
                overColor: '#095c09'
              },
              click: function(e){
                console.log(e)
              }
            });
            marker.data = item;
            marker.on("mouseover", R.mouseover);
            marker.on("mouseout", R.mouseout);
            markers.push(marker);
          });
          R.viewMarkers();
        }else{
          R.tip("时间段[" + beginTime + "，" + endTime + "]，没有降水量");
        }
      }
    });
  };
  R.viewMarkers = function(){
    if(! markers || markers.length == 0){
      return;
    }
    var zoom = map.getZoom();
    map.remove(markers);
    var z = 7
    if(zoom <= z){
      return;
    }
    var temp = [];
    var jl = 0;
    switch(zoom){
    case z + 1:
      jl = 150000;
      break;
    case z + 2: 
      jl = 110000;
      break;
    case z + 3:
      jl = 40000;
      break;
    default :
      jl = 10;
    }
    var h = $(".floattool .graphic_nav :radio[name=hour]:checked").val();
    var viewName = $(".floattool .graphic_nav .layer-pop .layer-arguments span[data-tag='stationName']").hasClass("check");
    var choose = $(".floattool .graphic_nav :radio[name=query]:checked").val();
    
    if(choose == 1){
      var d = new Date(Date.parse(endTime.replace(/-/g,"/")));
      d.setHours(d.getHours()-(h*1));
      beginTime = d.format("yyyy-MM-dd hh:mm:ss");
    }
    
    R.tip("时间段[" + beginTime + "，" + endTime + "]的降水量分布");
    
    markers.forEach(function(marker){
      var item = marker.data;
      var val = item['pre'+h+'h'];
      if(choose != 1){
        val = item.pre;
      }
      if(val > 0){
        var html = "<div class='stationDataClass' data-pre='"+item.pre.toFixed(1)+"'><label>" + (val.toFixed(1)) + "</label><span style='display:"+(viewName?'inline-block':'none')+"'>"+item.stationName+"</span></div>";
        if(choose < 3){
          html = "<div class='stationDataClass' data-pre='"+item.pre.toFixed(1)+"' data-pre1h='"+item.pre1h.toFixed(1)+"' data-pre3h='"+item.pre3h.toFixed(1)+"' data-pre6h='"+item.pre6h.toFixed(1)+"' data-pre12h='"+item.pre12h.toFixed(1)+"' data-pre24h='"+item.pre24h.toFixed(1)+"'><label>" + (val.toFixed(1)) + "</label><span style='display:"+(viewName?'inline-block':'none')+"'>"+item.stationName+"</span></div>";
        }
        var color = item['color'];
        if(choose < 3){
          color = item['color'+h+'h'];
        }
        marker.setIconLabel({
          innerHTML : html,
          style : {
            color : color
          }
        })
        if(temp.length == 0){
          map.add(marker);
          temp.push(marker)
        }else{
          for(var o in temp){
            var m = temp[o];
            var ll = m.getPosition().distance(marker.getPosition());
            if(ll > jl){
              map.add(marker);
              temp.push(marker)
              break;
            }
          }
        }
      }
    });
    R.buildData();
  };
  var oowin;
  R.mouseover = function(e) {
    var type = $(".floattool .graphic_nav :radio[name=query]:checked").val();
    oowin = new AMap.InfoWindow({ anchor: 'top-left', autoMove: true});
    var data = e.target.data;
    var html = '<div class="main"><table class="tab">' + 
      '<tr><td>站名：</td><td>'+(data.stationName ? data.stationName : '')+'</td></tr>'+
      '<tr><td>站号：</td><td>'+(data.stationId ? data.stationId : '')+'</td></tr>'+
      '<tr><td>省：</td><td>'+(data.province ? data.province : '')+'</td></tr>'+
      '<tr><td>市：</td><td>'+(data.city ? data.city : '')+'</td></tr>'+
      '<tr><td>区县：</td><td>'+(data.cnty ? data.cnty : '')+'</td></tr>';
    if(type == 1){
      html +=
        '<tr><td>过去1小时降水量：</td><td>'+(data.pre1h ? data.pre1h : '0')+'mm</td></tr>'+
        '<tr><td>过去3小时降水量：</td><td>'+(data.pre3h ? data.pre3h : '0')+'mm</td></tr>'+
        '<tr><td>过去6小时降水量：</td><td>'+(data.pre6h ? data.pre6h : '0')+'mm</td></tr>'+
        '<tr><td>过去12小时降水量：</td><td>'+(data.pre12h ? data.pre12h : '0')+'mm</td></tr>'+
        '<tr><td style="width:140px">过去24小时降水量：</td><td>'+(data.pre24h ? data.pre24h : '0')+'mm</td></tr>';
      html += '</table></div>';
      oowin.setContent('<div className="custom-infowindow input-card" class="foo--inside2" style="width:260px;height:380px">' + html + '</div>');
    }else if(type >= 2){
      html +=
        '<tr><td style="width:80px">降水量：</td><td>'+(data.pre ? data.pre : '0')+'mm</td></tr>';
      html += '</table></div>';
      oowin.setContent('<div className="custom-infowindow input-card" class="foo--inside2" style="width:260px;height:228px">' + html + '</div>');
    }
    oowin.open(map, e.target.getPosition());
  }
  
  R.mouseout = function(e) {
    map.remove(oowin)
  }
  
  R.tip = function(content){
    $("#tipWin .content").text(content);
    $("#tipWin").show();
    $("#tipWin .tabtop_rt").off().on("click", function(){
      $("#tipWin").hide();
    });
  }
  return R;
})();